package com.rongxue.service.Impl;

import com.rongxue.mapper.*;
import com.rongxue.pojo.*;
import com.rongxue.service.SuserService;
import com.rongxue.service.utils.P2PMessageUtils;
import com.rongxue.utils.CommonUtils;
import com.rongxue.utils.DateUtil;
import com.rongxue.utils.Page;
import com.rongxue.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.util.*;

/**
 * Created by yangweijian on 2018/1/15.
 */
@Service
@Transactional
class SuserServiceImpl implements SuserService {

    @Autowired
    private SUserMapper sUserMapper;

    @Autowired
    private SUserInterestCouponMapper sUserInterestCouponMapper;

    @Autowired
    private SUserRxgoldDetailMapper sUserRxgoldDetailMapper;

    @Autowired
    private SIntegralMapper sIntegralMapper;

    @Autowired
    private SMobileCodeMapper sMobileCodeMapper;

    @Autowired
    private SUserBankMapper sUserBankMapper;

    @Autowired
    private  SUserRedenvelopeMapper sUserRedenvelopeMapper;

    @Autowired
    private SUserAccountMapper sUserAccountMapper;

    @Autowired
    private SExperienceMapper sExperienceMapper;

    @Autowired
    private SUserDueDetailMapper sUserDueDetailMapper;


    //生成token
    public static String createToken(String mobile,String password,Long userId,Integer channel){
        Base64.Encoder  encoder= Base64.getEncoder();
        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        String md5 = p2PMessageUtils.getMD5(mobile).substring(8,24);
        String str =userId+"&"+channel;
        String encode = new String(encoder.encode(str.getBytes()));
        return  md5+password+encode;
    }
    @Override
    public ObjectResult insertToregist(XMLBean xmlBean) {
        //验证码校验
        MobileCode  mobileCode=  sMobileCodeMapper.selectCodeByMobile(xmlBean.getMobile());
        if(mobileCode != null && !mobileCode.getCode().equals(xmlBean.getMobile_auth_code())){
            return ObjectResult.build("0","验证码错误");
        }
        if(System.currentTimeMillis()-mobileCode.getSend_time()>5*60*1000){
            return ObjectResult.build("0","验证码失效");
        }

        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,Object> data = new HashMap<String,Object>();

        //是否注册
        map.put("mobile",xmlBean.getMobile());
        SUser suser = selectUserByMap(map);
        if(suser!=null) return ObjectResult.build("0","该用户已注册");


        //生成邀请码
        String invitations;
        while (true) {
            invitations = RandomUtil.getRandom(6);
            map.clear();
            map.put("invite",invitations);
            SUser sUser = sUserMapper.selectUserByMap(map);
            if (sUser == null) {
                break;
            }
        }
        //邀请人
        Long uid =0l;
        if(xmlBean.getInvite()!=null&&!"".equals(xmlBean.getInvite())){
            if (xmlBean.getInvite().length() == 6) {
                map.clear();
                map.put("invite", xmlBean.getInvite());
                SUser sUser = sUserMapper.selectUserByMap(map);
                if(sUser==null)return ObjectResult.build("0","邀请码错误");

                sUser.setIntegral(sUser.getIntegral()+5);
                sUserMapper.updateByPrimaryKeySelective(sUser);

                map.clear();
                map.put("userId",sUser.getId());
                map.put("type",1);
                map.put("integral",5);
                sIntegralMapper.insertIntegralByMap(map);

                uid = sUser.getId();
            } else if (xmlBean.getInvite().length() == 11) {
                map.clear();
                map.put("mobile", xmlBean.getInvite());
                SUser sUser = sUserMapper.selectUserByMap(map);
                if(sUser==null)return ObjectResult.build("0","邀请手机不存在");

                sUser.setIntegral(sUser.getIntegral()+5);
                sUserMapper.updateByPrimaryKeySelective(sUser);

                map.clear();
                map.put("userId",sUser.getId());
                map.put("type",1);
                map.put("integral",5);
                sIntegralMapper.insertIntegralByMap(map);

                uid = sUser.getId();
            }
        }
        SUser user = new SUser();
        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        //添加用户
        user.setMobile(xmlBean.getMobile());
        user.setUsername(xmlBean.getMobile());
        user.setPassword(p2PMessageUtils.getMD5(xmlBean.getPassword()));
        user.setAddTime(new Date());
        user.setDeviceSerialId(xmlBean.getDeviceSerialId());
        user.setPhoneSystemVersion(xmlBean.getPhoneSystemVersion());
        user.setDeviceType(xmlBean.getDevice_type());
        user.setChannel(xmlBean.getChannel());
        user.setAppVersion(xmlBean.getAppVersion());
        user.setProvince("");
        user.setInvite(invitations);
        user.setChannelId(sUserMapper.selectChannelId(xmlBean.getChannel()));
        user.setRegistrationId(xmlBean.getRegistration_id());
        user.setAddUserId(uid);
        user.setRealNameAuth(0);
        user.setCardType(0);
        user.setCardNoAuth(0);
        user.setMobileAuth(0);
        user.setEmailAuth(0);
        user.setStatus(2);
        sUserMapper.insertSelective(user);

        //初始化用户资金表
        map.clear();
        map.put("mobile",xmlBean.getMobile());
        SUser user1 = sUserMapper.selectUserByMap(map);
        sUserAccountMapper.inserUserAccountInit(user1.getId());

        map.clear();
        map.put("mobile",xmlBean.getMobile());
        SUser sUser = sUserMapper.selectUserByMap(map);
        Integer is_bank = sUserBankMapper.selectUserBankCoutByUserid(sUser.getId());

        //新手红包
        String[][] array = {{"50", "10000", "30", "60"}, {"150", "30000", "30", "60"}
                , {"250", "50000", "30", "60"}, {"100", "10000", "60", "60"}
                , {"300", "30000", "60", "60"},{"500", "50000", "60", "60"},{"300", "20000", "90", "90"}
                ,{"450", "30000", "900", "90"},{"900", "60000", "90", "90"},{"666", "20000", "180", "90"}
                ,{"1000", "30000", "180", "90"},{"2000", "60000", "180", "90"}};
        for (int i = 0; i < array.length; i++) {
            SUserRedenvelope sUserRedenvelope = new SUserRedenvelope();
            sUserRedenvelope.setTitle("新手认证红包");
            sUserRedenvelope.setContent("新手认证红包");
            sUserRedenvelope.setUserId(Integer.parseInt(sUser.getId()+""));
            sUserRedenvelope.setAmount(new BigDecimal(array[i][0]));
            sUserRedenvelope.setCreateTime(new Date());
            sUserRedenvelope.setMinInvest(new BigDecimal(array[i][1]));
            sUserRedenvelope.setMinDue(Integer.parseInt(array[i][2]));
            sUserRedenvelope.setExpireTime(DateUtil.addDateDay(new Date(), Integer.parseInt(array[i][3])));
            sUserRedenvelope.setStatus(0);
            sUserRedenvelopeMapper.insertSelective(sUserRedenvelope);
        }


        //返回数据
        String token =createToken(sUser.getMobile(),sUser.getPassword(),sUser.getId(),sUser.getChannelId());
        data.put("id",sUser.getId());
        data.put("username",sUser.getUsername());
        data.put("mobile",sUser.getMobile());
        data.put("avatar",sUser.getAvatar());
        data.put("level",sUser.getLevel());
        data.put("token",token);
        data.put("invite",sUser.getInvite());
        data.put("is_bank",is_bank);
        data.put("card_no_auth",sUser.getCardNoAuth());
        data.put("is_sign",user.getIs_sign());
        data.put("type",user.getType());

        return  ObjectResult.build("1","注册成功",data);
    }

    @Override
    public ObjectResult selectToLogin(XMLBean xmlBean, SUser user) {
        Map<String, Object> data = new HashMap<>();
        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        String md5 = p2PMessageUtils.getMD5(xmlBean.getPassword());
        if(!md5.equals(user.getPassword())){
            data.put("loginTypeTip","密码错误");
            return  ObjectResult.build("0","密码错误",data);
        }

        Integer is_bank = sUserBankMapper.selectUserBankCoutByUserid(user.getId());
        String token =createToken(user.getMobile(),user.getPassword(),user.getId(),user.getChannelId());

        data.put("id",user.getId());
        data.put("username",user.getUsername());
        data.put("mobile",user.getMobile());
        data.put("avatar",user.getAvatar());
        data.put("level",user.getLevel());
        data.put("token",token);
        data.put("invite",user.getInvite());
        data.put("is_bank",is_bank);
        data.put("card_no_auth",user.getCardNoAuth());
        data.put("loginTypeTip","登录成功");
        data.put("is_sign",user.getIs_sign());
        data.put("type",user.getType());
        return  ObjectResult.build("1","登录成功",data);
    }

    @Override
    public ObjectResult forget_pwd(XMLBean xmlBean) {
        MobileCode  mobileCode=  sMobileCodeMapper.selectCodeByMobile(xmlBean.getMobile());
        if(!mobileCode.getCode().equals(xmlBean.getMobile_auth_code())){
            return ObjectResult.build("0","验证码错误");
        }
        if(System.currentTimeMillis()-mobileCode.getSend_time()>5*60*1000){
            return ObjectResult.build("0","验证码失效");
        }
        P2PMessageUtils p2PMessageUtils = new P2PMessageUtils();
        String md5 = p2PMessageUtils.getMD5(xmlBean.getPassword());
        Map<String, Object> map = new HashMap<>();
        map.put("mobile",xmlBean.getMobile());
        SUser sUser = sUserMapper.selectUserByMap(map);
        if (md5.equals(sUser.getPassword())){
            return ObjectResult.build("0","不能与原密码相同");
        }

        SUser user = new SUser();
        user.setPassword(md5);
        user.setId(sUser.getId());

        sUserMapper.updateByPrimaryKeySelective(user);

        return ObjectResult.build("1","修改成功");
    }

    @Override
    public SUser selectUserByMap(Map<String,Object> map) {
        return sUserMapper.selectUserByMap(map);
    }

    @Override
    public void insertUser(SUser sUser) {
        sUserMapper.insert(sUser);
    }

    @Override
    public List<Rewards> selectRedpacketByUserId(String userId) {
        return sUserMapper.selectRedpacketByUserId(userId);
    }

    @Override
    public void updateRedpacketByUserId(String userId) {
        sUserMapper.updateRedpacketByUserId(userId);
    }

    @Override
    public List<Rewards> selectInterestcouponByUserId(String userId) {
        return sUserMapper.selectInterestcouponByUserId(userId);
    }

    @Override
    public void updateInterestcouponByUserId(String userId) {
        sUserMapper.updateRedpacketByUserId(userId);
    }

    @Override
    public List<Rewards> selectCashcouponByUserId(String userId) {
        return sUserMapper.selectCashcouponByUserId(userId);
    }

    @Override
    public void updateCashcouponByUserId(String userId) {
        sUserMapper.updateCashcouponByUserId(userId);
    }

    @Override
    public ObjectResult insertGold_conversion(XMLBean xmlBean) {
        Map<String,Object> map = new HashMap<String,Object>();
        String userId = CommonUtils.decToken(xmlBean.getToken());
        map.put("userId",userId);
        SUser sUser = sUserMapper.selectUserByMap(map);
        if(sUser ==null)return  ObjectResult.build("0","用户不存在");
        if(sUser.getIntegral()<1000) return ObjectResult.build("0","积分不足");

        //减去积分币
        map.put("integral",-1000);
        sUserMapper.updateIntegralAndRxgoldByMap(map);
        //添加加息券
        map.put("interestRate",1);
        map.put("expire_time",DateUtil.addDateDay(new Date(),30));
        int interestId = sUserInterestCouponMapper.insertRxgoldInterestCoupon(map);
        //添加积分越换记录

        map.put("type",4);

        sIntegralMapper.insertIntegralByMap(map);

        SUser user = sUserMapper.selectUserByMap(map);
        map.clear();
        map.put("integral",user.getIntegral());

        return ObjectResult.build("1","兑换成功",map);
    }

    @Override
    public List<SuserRxgoldDetail> selectUserRxgoldDetailByUserId(String userId) {
        return sUserRxgoldDetailMapper.selectUserRxgoldDetailByUserId(userId);
    }

    @Override
    public ObjectResult insertToSing_in(XMLBean xmlBean) {
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,Object> data = new HashMap<String,Object>();
        String userId = CommonUtils.decToken(xmlBean.getToken());
        if(userId==null||userId.equals("")) return ObjectResult.build("0","用户Id为空");
        Integer integer = sIntegralMapper.selectIntegralToday(userId);
        if(integer>0){
            return ObjectResult.build("0","今日已签到");
        }

        map.put("userId",Integer.parseInt(userId));
        map.put("integral",1);
        map.put("type",0);
        sIntegralMapper.insertIntegralByMap(map);//添加签到记录
        List<SIntegral> list = sIntegralMapper.selectSingnListByUserId(userId);

        int count =0;//连续签到天数
        for (int i =list.size()-1;i>=0;i--){
            boolean flag = DateUtil.formatDate(list.get(i).getAdd_time()).
                    equals(DateUtil.formatDate(DateUtil.addDateDay(new Date(),0-count)));
            if(!flag){
                break;
            }
            count++;
        }

        //连续签到增加额外积分
        if(count%7 == 0){
            SIntegral sIntegral = list.get(list.size() - 1);
            int i = count/7;
            switch (i){
                case 1 :sIntegral.setIntegral(sIntegral.getIntegral()+4); map.put("integral",5); break;
                case 2 :sIntegral.setIntegral(sIntegral.getIntegral()+9);map.put("integral",10); break;
                default:sIntegral.setIntegral(sIntegral.getIntegral()+14);map.put("integral",15); break;
            }
            sIntegralMapper.updateIntegral(sIntegral);
        }
//        switch (count){
//            case 5 : map.put("rx_gold",count); data.put("award",count); break;
//            case 10 : map.put("rx_gold",count); data.put("award",count);break;
//            case 20 : map.put("rx_gold",count); data.put("award",count);break;
//            case 30 : map.put("rx_gold",count); data.put("award",count);break;
//            default:  map.put("rx_gold",0); data.put("award",0);break;
//        }
        sUserMapper.updateIntegralAndRxgoldByMap(map);//跟新积分和融雪币
        SUser sUser = sUserMapper.selectUserByMap(map);
//       data.put("rx_gold",sUser.getRx_gold());
        data.put("integral",sUser.getIntegral());
        data.put("continuous",count);
        data.put("addIntegral",map.get("integral"));

        return ObjectResult.build("1","成功",data);
    }

    @Override
    public ObjectResult selectToSing_list(XMLBean xmlBean) {
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,Object> data = new HashMap<String,Object>();
        List<Day> dayList = new ArrayList<Day>();
        data.put("status",0);
        String userId = CommonUtils.decToken(xmlBean.getToken());
        if(userId==null||userId.equals("")) return ObjectResult.build("0","用户Id为空");
        List<SIntegral> list = sIntegralMapper.selectSingnListByUserId(userId);
        int count =0;//连续签到天数
        for (int i =list.size()-1;i>=0;i--){
            boolean flag = DateUtil.formatDate(list.get(i).getAdd_time()).
                    equals(DateUtil.formatDate(DateUtil.addDateDay(new Date(),0-count)));
            if(!flag){
                break;
            }
            if(count==0)  data.put("status",1);//当天已签到
            count++;
        }
        for (SIntegral sIntegral:list){
            Day day = new Day();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(sIntegral.getAdd_time());
            day.setDay(calendar.get(Calendar.DAY_OF_MONTH)+"");
            dayList.add(day);
        }
        map.put("userId",Integer.parseInt(userId));
        SUser sUser = sUserMapper.selectUserByMap(map);

        data.put("integral",sUser.getIntegral());
        data.put("continuous",count);
        data.put("list",dayList);

        return ObjectResult.build("1","成功",data);
    }

    @Override
    public ObjectResult insertLotteRule(XMLBean xmlBean) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        if(xmlBean.getToken()==null||xmlBean.getToken().equals(""))  return ObjectResult.build("0","token不存在");
        String userId = CommonUtils.decToken(xmlBean.getToken());
        map.put("userId",userId);
        SUser user = sUserMapper.selectUserByMap(map);
        if(user.getIntegral()<30){
            return ObjectResult.build("0","积分不足");
        }
        List<LotteRule> list = sUserMapper.selectLotteRuleAll();
        double probability = Math.random() * 100;
        double count = 0d;
        Integer id =null;//奖品id
        for (LotteRule lotteRule:list){
            count = count+lotteRule.getProbability();
            if(probability<count){
                id = lotteRule.getId();
                break;
            }
        }
        LotteRule lotteRule = sUserMapper.selectLotteRuleById(id);

        if(lotteRule.getType()==1) {//融雪币
            data.put("title","融雪币");
            map.clear();
            map.put("userId", userId);
            map.put("rx_gold", lotteRule.getAmount());
            map.put("integral",0);
            sUserMapper.updateIntegralAndRxgoldByMap(map);
        }
        else if(lotteRule.getType()==2){ //加息券
            data.put("title","加息券");
            SUserInterestCoupon interestCoupon = new SUserInterestCoupon();
            interestCoupon.setStatus(0);
            interestCoupon.setScope(0);
            interestCoupon.setScope(0);
            interestCoupon.setAddUserId(0);
            interestCoupon.setModifyUserId(0);
            interestCoupon.setProjectId(0);
            interestCoupon.setSubtitle("");
            interestCoupon.setCreateTime(0);
            interestCoupon.setTitle("积分抽奖加息券");
            interestCoupon.setSource("");
            interestCoupon.setIsDelete("0".getBytes()[0]);
            interestCoupon.setCouponId(0);
            interestCoupon.setAddTime(new Date());
            interestCoupon.setInterestRate(new BigDecimal(lotteRule.getAmount()));
            interestCoupon.setMinDue(lotteRule.getMin_day());
            interestCoupon.setMinInvest(new BigDecimal(lotteRule.getMin_money()));
            interestCoupon.setExpireTime(DateUtil.addDateDay(new Date(),lotteRule.getExpire_time()));
            interestCoupon.setScope(0);
            interestCoupon.setUserId(Integer.parseInt(userId));
            sUserInterestCouponMapper.insert(interestCoupon);
        }
        else if(lotteRule.getType()==3){//红包
            data.put("title","红包");
            SUserRedenvelope redenvelope = new SUserRedenvelope();
            redenvelope.setType(0);
            redenvelope.setStatus(0);
            redenvelope.setScope(0);
            redenvelope.setTitle("积分抽奖红包");
            redenvelope.setContent("积分抽红包");
            redenvelope.setCreateTime(new Date());
            redenvelope.setUserId(Integer.parseInt(userId));
            redenvelope.setAmount(new BigDecimal(lotteRule.getAmount()));
            redenvelope.setMinDue(lotteRule.getMin_day());
            redenvelope.setMinInvest(new BigDecimal(lotteRule.getMin_money()));
            redenvelope.setExpireTime(DateUtil.addDateDay(new Date(),lotteRule.getExpire_time()));
            redenvelope.setIsRead(0);
            redenvelope.setAddTime(0);
            redenvelope.setSource("");
            sUserRedenvelopeMapper.insert(redenvelope);
        }
        //减去30积分
        map.clear();
        map.put("userId",userId);
        map.put("rx_gold",0);
        map.put("integral",-30);
        sUserMapper.updateIntegralAndRxgoldByMap(map);

        data.put("type",lotteRule.getType());
        data.put("amount",lotteRule.getAmount());
        return ObjectResult.build("1","成功",data);
    }

    @Override
    public ObjectResult insertExperience(XMLBean xmlBean) {
        if (xmlBean.getToken() == null || xmlBean.getToken().equals("")) return ObjectResult.build("0", "token不存在");
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SExperience sExperience = sExperienceMapper.selectExperienceByUserId(userId);
        if(sExperience!=null){
            return ObjectResult.build("0","体验金已领取");
        }
        sExperienceMapper.insertExperience(userId);
        return ObjectResult.build("1","成功");
    }

    @Override
    public ObjectResult selectExperienceByUserId(XMLBean xmlBean) {
        if (xmlBean.getToken() == null || xmlBean.getToken().equals("")) return ObjectResult.build("0", "token不存在");
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SExperience sExperience = sExperienceMapper.selectExperienceByUserId(userId);
        if(sExperience==null) return ObjectResult.build("1","成功",0);
        return ObjectResult.build("1","成功",1);
    }

    @Override
    public ObjectResult back(XMLBean xmlBean) {
        if (xmlBean.getToken() == null || xmlBean.getToken().equals("")) return ObjectResult.build("0", "token不存在");
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SUserAccount sUserAccount = sUserAccountMapper.selectUserAccountByUserId(Long.parseLong(userId));
        map.put("wait_interest",sUserAccount.getWait_interest().toString());//代收利息
        map.put("wait_capital",sUserAccount.getWaitCapital().toString());//代收本金


        data.put("status",xmlBean.getType());//1回款中2已回款
        data.put("userId",userId);
        List<SUserDueDetail> sUserDueDetails = sUserDueDetailMapper.selectDueDetailByMap(data);

        Page<SUserDueDetail> page = new Page<>();
        page.setP(xmlBean.getP());
        page.setPageSize(10d);
        List<SUserDueDetail> content = page.getPageContent(sUserDueDetails);
        for (SUserDueDetail sUserDueDetail:content){
            sUserDueDetail.setAdd_time(sUserDueDetail.getAdd_time().substring(0,10));
            sUserDueDetail.setDue_time(sUserDueDetail.getDue_time().substring(0,10));
        }

        map.put("list",content);

        return ObjectResult.build("1","成功",map);
    }
}
